@extends('layouts/main')
@section('content')
    <style>
        .layui-body{overflow-x: scroll;}
        .error-tip{font-size: 16px;margin-top: 10px;margin-bottom: 10px;}
        .op-field-item{width: 140px;}
    </style>
    <div style="padding: 15px;">
        @if($db_name)
            <input type="hidden" id="sql_data" value="{{$sql}}">
            <button class="layui-btn layui-btn-danger" type="button"  onclick="dropTable('{{$table_name}}', '{{$db_name}}')">删除表</button>
            <a class="layui-btn" type="button" href="/index/insertLine?db_name={{$db_name}}&table_name={{$table_name}}">插入</a>
            <br>
            <div class="layui-tab layui-tab-brief" lay-filter="docDemoTabBrief">
                <ul class="layui-tab-title">
                    @if($tab=='record')
                        <li class="layui-this">浏览</li>
                    @else
                        <li><a href="/index/record?db_name={{$db_name}}&table_name={{$table_name}}">浏览</a></li>
                    @endif
                    @if($tab=='structure')
                        <li class="layui-this">结构</li>
                    @else
                        <li><a href="/index/structure?db_name={{$db_name}}&table_name={{$table_name}}">结构</a></li>
                    @endif
                    @if($tab=='operation')
                        <li>操作</li>
                    @else
                        <li><a href="/index/operation?db_name={{$db_name}}&table_name={{$table_name}}">操作</a></li>
                    @endif
            </ul>
                <div class="layui-tab-content">
                </div>
            </div>
        @if($table_name)表名：{{$table_name}}@else 执行原生SQL查询 @endif
            <table class="layui-table">
                <colgroup>
                    <col width="150">
                    <col width="200">
                    <col>
                </colgroup>
                <thead>
                <tr id="table-field">
                </tr>
                </thead>
                <tbody id="table-data-list">
                </tbody>
            </table>
        <div class="error-tip"></div>
            <div>共<span id="total-page">0</span>页，<span id="total-rows">0</span>条数据<div id="pager"></div></div>
        @else
            请在左侧选择一个数据库以查看该数据库下的表
        @endif
    </div>
    <script>
        layui.use('element', function(){
            var element = layui.element;

            //…
        });


        $(function () {
            page = 1;
            limit = 20;
            total = 0;
            total_page = 0;
            sql = '{{$sql}}';
            var sql = $('#sql_data').val();
            if (sql) {
                executeSql('{{$sql}}');
            } else {
                // getFieldData();
                getList();
            }



            function getFieldData() {
                var index = layer.load(1);
                $.ajax({
                    url:'/index/getFieldsData',
                    type: 'get',
                    dataType: 'json',
                    data: {
                        db_name: '{{$db_name}}',
                        table_name: '{{$table_name}}',
                    },
                    success: function (res) {
                        layer.close(index);
                        if (res.status == 200) {
                            for (var i=0; i< res.data.length; i++) {
                                $('#table-field').append('<td>'+res.data[i].column_name+' '+res.data[i].column_comment+'</td>');
                            }
                        } else {
                            $('.error-tip').html('<font color="red">执行出错！错误信息：'+res.msg+'</font>')
                        }

                    }
                })
            }

            function getList(){
                var index = layer.load(1);
                $.ajax({
                    url:'/index/getListData',
                    type: 'get',
                    dataType: 'json',
                    data: {
                        db_name: '{{$db_name}}',
                        table_name: '{{$table_name}}',
                        page: page,
                        limit: limit,
                    },
                    success: function (res) {
                        layer.close(index);
                        if (res.status == 200) {
                            page = res.data.page;
                            limit = res.data.limit;
                            total = res.data.total;
                            total_page = res.data.total_page;
                            $('#table-data-list').empty();
                            $('#table-field').empty();
                            $('#table-field').append('<td class="op-field-item">操作</td>');
                            for (var i = 0; i < res.data.list.field.length; i++) {
                                encodeStr = res.data.list.field[i];
                                if (encodeStr != null) {
                                    encodeStr = htmlEncode(res.data.list.field[i])
                                    if (encodeStr.length > 400 ) {
                                        encodeStr = encodeStr.substring(0, 400)+'......';
                                    }
                                }
                                $('#table-field').append('<td title="'+encodeStr+'">'+encodeStr+' '+'</td>');
                            }
                            for (var i=0; i< res.data.list.result.length; i++) {
                                var item = Object.values(res.data.list.result[i]);
                                var html = '';
                                var itemId = 0;
                                for (var j=0; j<item.length/2; j++){
                                    itemId = item[0];
                                    var encodeStr = item[j];
                                    if (encodeStr != null) {
                                        encodeStr = htmlEncode(encodeStr);
                                        if (encodeStr.length > 400 ) {
                                            encodeStr = encodeStr.substring(0, 400)+'......';
                                        }
                                    }

                                    html = html + '<td title="'+item[j]+'">'+encodeStr+'</td>';
                                }
                                var opItem = '<td><button class="layui-btn" onclick="gotoEditPage(\''+ itemId +'\')">编辑</button><button class="layui-btn layui-btn-danger" onclick="delLine(\''+ itemId +'\')">删除</button></td>'
                                $('#table-data-list').append('<tr>'+ opItem +html+'</tr>');
                            }
                            $('#total-page').text(total_page);
                            $('#total-rows').text(total);
                            showPager(page, limit, total, 1);
                        } else {
                            $('.error-tip').html('<font color="red">执行出错！错误信息：'+res.msg+'</font>')
                        }

                    }
                })
            }

            function executeSql(sql) {
                var index = layer.load(1);
                $.ajax({
                    url:'/index/getSqlResult',
                    type: 'get',
                    dataType: 'json',
                    data: {
                        db_name: '{{$db_name}}',
                        sql: sql,
                        page: page,
                        //limit: limit,
                    },
                    success: function (res) {
                        layer.close(index);
                        if (res.status == 200) {
                            console.log(res);
                            page = res.data.page;
                            limit = res.data.limit;
                            total = res.data.total;
                            total_page = res.data.total_page;
                            $('#table-field').empty();
                            $('#table-data-list').empty();
                            var field = res.data.list.field;
                            var data_list = res.data.list.result;

                            for (var i=0; i<field.length; i++) {
                                $('#table-field').append('<td>'+field[i]+' '+'</td>');
                            }
                            for (var i=0; i< data_list.length; i++) {
                                var html = '';
                                var item = Object.values(data_list[i]);
                                for (var j=0; j<item.length/2; j++){
                                    var encodeStr = item[j];
                                    if (encodeStr != null) {
                                        encodeStr = htmlEncode(encodeStr);
                                        if (encodeStr.length > 400 ) {
                                            encodeStr = encodeStr.substring(0, 400)+'......';
                                        }
                                    }
                                    html = html + '<td title="'+item[j]+'">'+encodeStr+'</td>';
                                }
                                $('#table-data-list').append('<tr>'+html+'</tr>');
                            }
                            $('#total-page').text(total_page);
                            $('#total-rows').text(total);
                            showPager(page, limit, total, 2);
                        } else {
                            $('.error-tip').html('<font color="red">执行出错，请检查SQL语句！错误信息：'+res.msg+'</font>')
                        }

                    }
                })
            }

            function showPager(curr, limit, total, type) {
                layui.use(['laypage', 'layer'], function() {
                    var laypage = layui.laypage
                        , layer = layui.layer;

                    //总页数大于页码总数
                    laypage.render({
                        elem: 'pager'
                        ,curr: curr
                        ,limit: limit
                        ,count: total //数据总数
                        ,jump: function(obj, first){
                            console.log(obj.curr)
                            if (!first) {
                                page = obj.curr
                                if (type == 2) {
                                    executeSql(sql);
                                } else {
                                    getList();
                                }

                            }

                        }
                    });
                });
            }

        })

        function delLine(id) {
            var sql = "DELETE FROM {{$table_name}} WHERE id='"+ id +"'"
            var warn = "是否执行："+ sql +"?";
            layer.confirm(warn, {
                title: '删除确认',
                btn: ['我已确定','再想想'],
                icon: 7,
            }, function(){
                var postData = {
                    db_name: '{{$db_name}}',
                    sql: sql,
                    _token: $('meta[name="csrf-token"]').attr('content'),
                };
                var res = sendAjaxRequest('POST', '/database/executeSql', postData, false);
                if (res.status == 0) {
                    layer.msg('删除成功');
                    reloadPage();
                } else {
                    layer.msg(res.msg, {
                        icon: 5,
                        time: 3000,
                        anim: 6,
                        closeBtn: 1,
                    });
                }
            }, function(){
                // 取消操作
            });
        }

        function gotoEditPage(id) {
            location.href = '/index/editTableLine?db_name={{$db_name}}&table_name={{$table_name}}&data_id='+id;
        }



    </script>
@endsection